<?php 
class Sell extends CI_Controller {
	
	function __construct()
	{
		parent::__construct();
		$this->load->library('session');
		$this->load->library('form_validation');
		// $this->load->library('encrypt');
		$this->load->library('fpdf');
    $this->load->model('mmaster');
    $this->load->model('mglobal');
		$this->load->model('msell');
		$this->is_logged_in();
		#$this->mjadwal->saveLog();
		$this->load->helper('url');
    $this->load->library('enc');
	}

	function is_logged_in()
	{
		$is_logged_in = $this->session->userdata('is_logged_in');
		if(!isset($is_logged_in) || $is_logged_in != true)
		{
			redirect(base_url() .'index.php/login');
		}		
	}

	function index($lastId= "")
	{
		$data['lastId'] = $lastId;
		$data['template'] 	= "shell/smooth";
		$data['main_view']  = 'f-sell';
		$this->load->view($data['template'],$data);
	}
	
	function getItemList($sales_id="")
	{
    $sales_id = $this->input->post("sales_id");
		$data = $this->msell->getItems($sales_id);
		echo json_encode($data);
	}

  //ambil data dari table v_combo_event_selling atau v_combo_event_selling_ds untuk populate combobox list
  function getProgram($sid="", $program="")
  {
    $data = $this->msell->getProgram($sid, $program); //Search DB   
    echo json_encode($data);
  }

	//ambil list outlet
    function getOutletList(){
      $user_group_id = $this->input->post("user_group_id");
      $user_id       = $this->input->post("sales_id");
      $data = $this->msell->get_outlet_list($user_group_id, $user_id); //Search DB
      echo json_encode($data);
    }
	
  public function get_program( $user_group_id, $channel_id )
  {
    $data = $this->msell->get_program( $user_group_id, $channel_id );
    echo json_encode($data);
  }

	function newsell() {
    $data['template']  = "shell/smooth";
    $data['main_view'] = "trans/sell_create";
    $cluster_id = $this->mglobal->user_cluster($this->session->userdata('username'));
    $data["territory"] = $this->mglobal->get_territory( $cluster_id ); // kayaknya ini enggak dipakai
    $data['salesID']   = $this->msell->sell_in_sales_team($cluster_id);
		$data['termin']    = $this->termin();
		
    $teritori = explode('>', $this->mglobal->getTerritoryPath());
    $data['region'] = $teritori[0];
    $data['cluster'] = $teritori[1];


    ####### BAGIAN INI UNTUK MENYIMPAN KE DATABASE #################################################
    $sell_date    = $this->input->post("sell_in_date");
    $partner_id   = $this->input->post("partner_id");
    $sales_id     = explode("_", $this->input->post("sales_id"));
    $iccid        = $this->input->post('iccid');
    $top_id       = $this->input->post("term_of_payment");

    $program_id[] = $this->input->post("program_nasional");
    $programC     = $this->input->post("program_cluster");
    if($programC)
      { $program_id[] = $programC; }

    $this->form_validation->set_rules('sell_in_date',     'Tanggal Sell In',   'required');
    $this->form_validation->set_rules('sales_id',         'Nama Sales',        'required');
    $this->form_validation->set_rules('partner_id',       'Nama Partner',      'required');
    $this->form_validation->set_rules('iccid[]',          'Item',              'required');
    $this->form_validation->set_rules('program_nasional', 'Program Nasional',  'required');
    $this->form_validation->set_rules('term_of_payment',  'Termin Pembayaran', 'required');

    $dup_iccid = array(); $new_iccid = array();

    if ($this->form_validation->run() != false) {
      $duplicate_iccid = array_count_values($iccid);    // Returns ['iccid_0']=>counts, [iccid_1]=>counts
      $unique_iccid    = array_unique($iccid);          // Returns [0]=>"iccid_0", [1]=>"iccid_1"
      $duplicate_iccid; 
      $unique_iccid; 
      foreach ($unique_iccid as $key) {   // $key become unique_iccid value: iccid_0, iccid_1
        if($duplicate_iccid[$key] == 1) 
          { $new_iccid[] = $key; }        // if the count equal to 1, create new array, the array is now unique
        else 
          { $dup_iccid[] = $key; }        // if the count greater then to 1, create new array contains unique iccid above.
      }

      $iccidsama='';
      foreach ($dup_iccid as $a)
        { $iccidsama .= $a.', '; }
      // Validate each unique iccids and return as new array named valid_iccid
      $i = 0;
      $valid_iccid = array();
      foreach ($new_iccid as $key) { 
        $valid_iccid[] = $this->_validate_item($key, $sales_id[1], $partner_id); 
        if ($valid_iccid[$i] == null)
          { unset($valid_iccid[$i]) ;}
        $i++;
      }

      if (count($valid_iccid) != 0 ) {  // if array is not null, save transactions
        $this->db->trans_begin();

        $sell_in_id = $this->msell->save_sell_in($sales_id[1], $partner_id, $top_id, $sell_date);
        foreach ($program_id as $program) {
          $program_sell = $this->msell->save_sell_program($sell_in_id, $program, $sell_date);
        }
        foreach ($valid_iccid as $item) {
          $this->msell->save_sell_detail($sell_in_id, $item); 
        }

        // Integrasikan data sell in sebagai stock outlet ke aplikasi SRIs
        $db_sri = $this->load->database('Retails', TRUE);
        $db_sri->trans_begin();
          $this->load->model('mintegrasi');
          $this->mintegrasi->StockIn($partner_id, $valid_iccid, $sell_in_id, 'sell_in');

        // Log untuk AuditTrail kita pindah ke sini dan formatnya kita jadikan json seperti yang ada di mobile agar mudah dibaca
        $this->mglobal->saveLog('sell_in', 'create', json_encode(array('trx_id' => $sell_in_id, 'iccid' => $valid_iccid, 'program_id' => $program_id) ) );

        if ($this->db->trans_status() === FALSE OR $db_sri->trans_status() === FALSE)
        {
          $this->db->trans_rollback();
          $db_sri->trans_rollback();
           $this->session->set_flashdata('message', 'Tidak ada item yang valid');
           redirect(base_url() . "index.php/sell/newsell");
        }
        else
        {
          $this->db->trans_commit();
          $db_sri->trans_commit();
          if (count($dup_iccid) != 0) { $message = "Data berhasil disimpan dengan nomor transaksi $sell_in_id, terdapat duplikat ICCID: $iccidsama" ; }
          else {$message = "Data berhasil disimpan dengan nomor transaksi $sell_in_id" ; }
          $this->session->set_flashdata('message', $message);
          redirect(base_url() . "index.php/sell");
        }
      }
    } // end of form_validation
    else {
      if ($teritori[1]) 
        { $this->load->view($data['template'], $data, FALSE); }
      else
        { redirect("index.php/cluster"); }
      // $this->session->set_flashdata('message', "Anda harus memberi tanda centang pada item yang akan di jual");
      // redirect(base_url() . "index.php/sell/newsell/" );
    }
    ################################################################################################
  }
	
	public function termin() {
		$termin = $this->msell->termins();
		return $termin;
	}

  public function detail($eId)
  {
    $template          = "shell/smooth";
    $data["main_view"] = 'trans/sell_detail';
    $trx_id            = ltrim($this->enc->defog($eId), '0');
    $data["sell"]      = $this->msell->get_sell_in_detail($trx_id);
    $this->load->view($template, $data, FALSE);
  }

  // untuk manage data yang ditampilkan pada grid view
    public function read() {

    $cluster_id = $this->mglobal->user_cluster($this->session->userdata("username"));
    // $cluster_id["cluster_id"]; 
    	//edited by Alfin Akhret
		if($this->session->userdata('is_self_service') == 1)
		{
			$result = $this->msell->getAllSellinCurrentUser();
		}
		else
		{
    		$result = $this->msell->getAllSellin($cluster_id);
    }
    	
    	//encode the sell_in_id
    	$x=0;
    	foreach ($result['aaData'] as $r) 
    	{
            $result['aaData'][$x++][1] = $this->enc->fogit($r[1]);
      }

    //penambahan nomor statis untuk grid SSP
        $start=$_GET['iDisplayStart'];
        $result['iDisplayStart']=$start;
		echo json_encode($result);
	}

	// added by: alfin akhret
	function defoger()
    {
    	//decode
        $result = $this->enc->defog($this->input->post('str'));
        echo $result;  
    }
	
	//process posted form data (the requested items like province)
    function load_sell($iccid){
        $data['test'] = $this->msell->getSell($iccid); //Search DB
        
        if('IS_AJAX')
        {
            echo json_encode($data['test']);
        }
    }
		
	//ambil daftar iccid untuk ditampilkan pada textbox autocomplete, melalui method getRelatedIccid di model msell
	function getRelatedIccid($salesId, $term){
        
        $data['relatedIccid'] = $this->msell->getRelatedIccid($salesId, $term); //Search DB
        
        if('IS_AJAX')
        {
            echo json_encode($data['relatedIccid']);
        }
    }
	
	
	//concate id pada row table tertentu untuk keperluan view
	public function concateId($id)
	{
		$tempId = "" . $id;
		if (strlen($tempId) < 4)
		{
			for($ii=strlen($tempId); $ii<4; $ii++)
			{
				$tempId = '0' . $tempId;
			}
		}
		return $tempId;
	}
	
	//proses data untuk halaman detail
	function getDetail($id1='', $id2='')
	{
		// $sell_id = $id1;

		//edited by : alfin akhret
		$sell_id = $this->enc->defog($id1); //decode the fog.
		$sell_id = ltrim($sell_id, '0'); //trim the leading zero

		$temp = $this->msell->getById($sell_id);
		$sales_id = $temp->user_id;
		
		$temp = "";
		$temp = $this->msell->getClusterName($this->session->userdata('username'));
		$data['ter_name'] 	= $temp[0]['territory_name'];
		$ter_id 			= $temp[0]['territory_id'];
		
		$list = $this->pdfAndDetail($sell_id, $ter_id);
		$data['termin'] = $list[2]->top_name;
		// print_r($list); die;

		$data['strId'] = $list[0];
		$data['dist'] = $list[1];
		$data['sell_in'] = $list[2];
		$data['sales_name'] = $list[3];
		$data['sell_in_detail'] = $list[4];		
		//$data['outlet_name'] = $data['sell_in']->channel_id;
		$data['outlet_name'] = $this->msell->getPartner($data['sell_in']->channel_id);
		
		
		$data['program_ho'] = $this->msell->getDetailProgram($sell_id, "ho", $sales_id);
		$data['program_cluster'] = $this->msell->getDetailProgram($sell_id, "cl", $sales_id);

		for($ii=0;$ii<count($list[4]);$ii++)	
		{
			$data['itemDetail'][$ii] = $list[5+$ii];
			$data['detailCounter'] = $ii + 1;
		}
		
		$data['template'] 	= "shell/smooth";
		$data['main_view']  = 'f-sell-detail';
		$this->load->view($data['template'],$data);
		
	
	}
	
	//proses data untuk men-generate file pdf dan detail view
	function pdfAndDetail($sell_id, $ter_id)
	{
		$list = array();
		
		$list[0] = $this->concateId($sell_id);
		
		$this->db->select('distributor_name, distributor_address');
		$this->db->where('territory_id', $ter_id);
		$q = $this->db->get('t_mtr_distributor');
		$list[1] = $q->result_array();
		$list[2] = $this->msell->getById($sell_id);
		$list[3] = $this->msell->getNikName($list[2]->user_id);
		
		// $this->db->select('*');
		// $this->db->where('sell_in_id', $sell_id);
		// $q = $this->db->get('t_trx_sell_in_detail');
		$q = $this->db->get_where('t_trx_sell_in_detail', array('sell_in_id' => $sell_id));
		$list[4] = $q->result_array();
		
		for($ii=0;$ii<count($list[4]);$ii++)
		{
			$list[$ii+5] = $this->msell->getItemDetail($list[4][$ii]['iccid']);
		}
			
		return $list;
	
	}
	
  private function _validate_item($iccid, $sales_id, $channel_id)
  {
    $item = $this->msell->validate_item($iccid, $sales_id, $channel_id);
    return $item;
  }

  function eload($action = "", $eload_id = "")
  {
    $cluster_id = $this->mglobal->user_cluster($this->session->userdata('username'));
    $template = "shell/smooth";
    if(!$action) {
      $data['main_view'] = "trans/eload_grid"; 
    }
    else{
      if($action == 'create') {
        $data['main_view'] = "trans/eload";
        $data['sales']     = $this->msell->sell_in_sales_team($cluster_id);
        // $data['sales']     = $this->msell->getSalesID($this->session->userdata('username'));
      }

      elseif ($action == 'detail') {
        $data['main_view'] = 'trans/eload_detail';
        $data['eload']     = $this->msell->eload_detail($eload_id);
      }
    }

    $teritori = explode('>', $this->mglobal->getTerritoryPath());
    $data['region'] = $teritori[0];
    $data['cluster'] = $teritori[1];
    if ($teritori[1]) {
      $this->load->view($template, $data, FALSE);
    }
    else
    {
      $this->session->set_flashdata('message', 'Silakan pilih cluster');
      redirect("index.php/cluster");
    }
  }

  public function close_eload()
  {
    $eload_id = $this->input->post('data');
    $data = $this->msell->close_eload($eload_id);
    echo json_encode($data);
  }
  
  public function eload_grid($value='')
  {
    $cluster_id = $this->mglobal->user_cluster($this->session->userdata("username"));
    
    $result = $this->msell->get_all_eload($cluster_id);

    //penambahan nomor statis untuk grid SSP
    $start=$_GET['iDisplayStart'];
    $result['iDisplayStart']=$start;
    echo json_encode($result);
  }

  function save_eload() {
    $sales_id     = explode(';',$this->input->post('sales_id'));
    $sell_date    = $this->input->post('sell_in_date');
    $eload_number = $this->input->post('eload_number');
    $channel_id   = $this->input->post('channel_id');
    $nominal      = $this->input->post('eload_nominal');

    for ($i=0; $i < count($channel_id); $i++) { 
      if($nominal[$i] != '0' AND $nominal[$i] != "") {
        $eload[] = array(
          "sales_id"     => $sales_id[0], 
          "channel_id"   => $channel_id[$i], 
          "amount"       => $nominal[$i], 
          "eload_number" => $eload_number[$i],
          "sell_date"    => $sell_date,
          "created_by"   => $this->session->userdata('username'),
          "created_on"   => date('Y-m-d H:i:s'),
          "access_via"   => 'web'
          );
      }
    }

    if(count($eload)) {
      $eload_status = $this->msell->save_eload_sell($eload);
    }

    if($eload_status) { 
      $this->session->set_flashdata('message', 'Berhasil menyimpan transaksi eload');
      redirect(base_url('index.php/sell/eload'));
    }
    else { 
      $this->session->set_flashdata('message', 'Transaksi eload gagal disimpan');
      redirect(base_url('index.php/sell/eload'));
    }

  }
}